package com.yugao.fintech.draper.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yugao.fintech.draper.admin.entity.SysLoginLog;
import com.yugao.fintech.draper.admin.mapper.LoginLogMapper;
import com.yugao.fintech.draper.admin.service.LoginLogService;
import com.yugao.fintech.draper.admin.convert.OperLogConvert;
import com.yugao.fintech.draper.auth.dto.LoginLogDTO;
import com.yugao.fintech.draper.admin.param.OperLogQuery;
import com.yugao.fintech.draper.datasource.base.BaseCreateEntity;
import com.yugao.fintech.draper.log.enums.BusinessType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class LoginLogServiceImpl implements LoginLogService {
	@Autowired
	private LoginLogMapper loginLogMapper;

	@Override
	public IPage<LoginLogDTO> pageQuery(OperLogQuery operLogQuery) {
		QueryWrapper<SysLoginLog> queryWrapper = Wrappers.query();
		if (Objects.isNull(operLogQuery.getBusinessType())) {
			queryWrapper.ne(StringUtils.camelToUnderline(SysLoginLog.Fields.businessType), BusinessType.GRANT);
		} else {
			queryWrapper.eq(StringUtils.camelToUnderline(SysLoginLog.Fields.businessType), operLogQuery.getBusinessType());
		}
		queryWrapper.like(StrUtil.isNotBlank(operLogQuery.getTitle()), SysLoginLog.Fields.title, operLogQuery.getTitle())
				.orderByDesc(StringUtils.camelToUnderline(BaseCreateEntity.Fields.createTime));
		Page<SysLoginLog> pageInfo = loginLogMapper.selectPage(Page.of(operLogQuery.getPageNum(), operLogQuery.getPageSize()), queryWrapper);
		return OperLogConvert.INSTANCE.convert(pageInfo);
	}

	@Override
	public LoginLogDTO findById(Long id) {
		SysLoginLog operLog = loginLogMapper.selectById(id);
		return OperLogConvert.INSTANCE.convert(operLog);
	}

	@Override
	public List<LoginLogDTO> findAll() {
		List<SysLoginLog> operLogList = loginLogMapper.selectList(Wrappers.emptyWrapper());
		return OperLogConvert.INSTANCE.convert(operLogList);
	}

	@Override
	public Boolean addOperLog(LoginLogDTO loginLogDTO) {
		SysLoginLog operLog = OperLogConvert.INSTANCE.convert(loginLogDTO);
		return loginLogMapper.insert(operLog) > 0;
	}

	@Override
	public Boolean updateOperLog(LoginLogDTO loginLogDTO) {
		SysLoginLog operLog = OperLogConvert.INSTANCE.convert(loginLogDTO);
		return loginLogMapper.updateById(operLog) > 0;
	}

	@Override
	public Boolean deleteOperLog(Long id) {
		return loginLogMapper.deleteById(id) > 0;
	}
}